package org.example.ams;

import org.example.ams.entity.system.SysUser;
import org.example.ams.service.system.ISysUserService;
import org.example.ams.websocket.WSServer;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import javax.annotation.PostConstruct;
import java.util.Date;


@EnableDiscoveryClient
@EnableScheduling
@MapperScan(basePackages = {"org.example.ams.dao.system"})
@SpringBootApplication
public class AMSApplication {

    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @Value("${ws.endpoint}")
    private String wsEndpoint;
    @Value("${ws.port}")
    private Integer wsPort;
    @Value("${default-password}")
    private String defaultPassword;
    @Value("${admin-usercode}")
    private String adminUserCode;


    public static void main(String[] args) {
        SpringApplication.run(AMSApplication.class, args);
    }


    /**
     * 初始化系统
     */
    @PostConstruct
    public void initSystem() {
        // ========================== 自动创建管理员账号 ======================================
        /**
         * 因为系统超级管理员用户不能直接添加，所以系统启用时判断系统有没超级管理员账号，没有就自动创建
         */
        String systemDefaultUserName = "admin";
        SysUser admin = sysUserService.queryByUsername(systemDefaultUserName);
        if (admin == null) {
            admin = new SysUser();
            admin.setUserCode(adminUserCode);
            admin.setUsername(systemDefaultUserName);
            admin.setPassword(defaultPassword);
            admin.setNameZh("超级管理员");
            admin.setStatus(true);
            admin.setIsValid(true);
            admin.setCreateTime(new Date());
            admin.setUpdateTime(new Date());
            admin.setIsAdmin(true);
            sysUserService.addUser(admin);
        }
        // =================================================================================



        // ========================== 启动websocket服务 ======================================
        threadPoolTaskExecutor.execute(new Runnable() {
            @Override
            public void run() {
                new WSServer(wsEndpoint,wsPort).start();
            }
        });
        // =================================================================================
    }
}
